import React, { Component } from 'react'
import { Table, Modal, Form, Checkbox, TimePicker, InputNumber, Switch, message } from 'antd'
import { SearchCol, SearchRow } from '@/styled/form';
const CheckboxGroup = Checkbox.Group;
import styles from './style.less'
import moment from 'moment'
import { toWeekendsArr, toNumArr } from './utils'
import { connect } from 'dva'
const format = 'HH:mm';
const plainOptions = ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期日'];
let defaultCheckedList = ['星期一', '星期二',];
const ONE_PAGE_SIZE = 10
interface ShowModalP {
  title: string,
  type: number,
  targetObj: {

  }
}
@connect(({ message }) => ({
  listSetting: message.list || {},
  dispatchFlag: message.dispatchFlag
}))
class MessageTable extends Component<any, any> {
  state = {
    current: 1,
    visible: false,
    title: '',
    checkedList: defaultCheckedList,
    indeterminate: true,
    checkAll: false,
  }

  //全选和全不选
  onChange = checkedList => {
    this.setState({
      checkedList,
      indeterminate: !!checkedList.length && checkedList.length < plainOptions.length,
      checkAll: checkedList.length === plainOptions.length,
    });
  };

  onCheckAllChange = e => {
    const { setFieldsValue } = this.props.form

    this.setState({
      checkedList: e.target.checked ? setFieldsValue({ times: plainOptions }) : setFieldsValue({ times: [] }),
      indeterminate: false,
      checkAll: e.target.checked,
    });
  };
  //处理ok提交表单
  handleOk = e => {
    const { form, dispatch, user, dispatchFlag } = this.props;

    form.validateFields((err, values) => {

      const payloadMessage = {
        id: localStorage.getItem('modifId'),
        valueRule:{
          isMessage: values.isOpen ? 1 : 0,
          message:{
            mins: values.gapMins,
            times: values.gapTimes,
            beginTime: moment(values.beginTime).format(format),
            endTime: moment(values.endTime).format(format),
            dayOfWeek: toNumArr(values.times)
          }
        }
      }
      const payloadTelephone = {
        id: localStorage.getItem('modifId'),
        valueRule:{
          isTelephone: values.isOpen ? 1: 0,
          telephone:{
            mins: values.gapMins,
            times: values.gapTimes,
            beginTime: moment(values.beginTime).format(format),
            endTime: moment(values.endTime).format(format),
            dayOfWeek: toNumArr(values.times)
          }
        }
      }

      //根据dispatchFlag判断是人员还是消控室调用不同的dispatch
      if (!err) {
      
        //电话通知的表单提交
        if (localStorage.getItem('submitType') === '1') {
          dispatchFlag === 1 ? 
          dispatch({type: 'message/modifRoom',payload:payloadTelephone}):
          dispatch({type: 'message/modifPeople',payload:payloadTelephone});
          
          localStorage.setItem('submitType', '2')
        } else {
          dispatchFlag === 1 ?
          dispatch({type: 'message/modifRoom',payload:payloadMessage}) :
          dispatch({type: 'message/modifPeople',payload:payloadMessage});
        }
        this.setState({
          visible: false
        })
      } else {
        // notification['error']({
        //   message: `修改失败`,
        //   description: '字段验证不通过',
        // });

      }
    })
  };
  componentDidMount() {
    const { dispatch } = this.props
    dispatch({
      type: 'message/queryPage',
      payload: {
        pageNum: 1,
        pageSize: 10
      }
    })
  }
  //打开modal表单回显
  showModal = (data: any) => {
    const { dispatch } = this.props
    localStorage.setItem('modifId', data.targetObj.id)      
    dispatch({ type: 'message/modifDispatchFlag', payload: data.targetObj.type}) //修改dispatchFlag
    const targetObj = data.targetObj
    const valueRuleList = targetObj.valueRuleList
    const { setFieldsValue } = this.props.form
    //判断是否全选点击打开弹框
    let isCheckAll = false;
    if( valueRuleList && valueRuleList.telephone && valueRuleList.message ){
      let telephoneWeek = valueRuleList.telephone.dayOfWeek
      let messageWeek = valueRuleList.message.dayOfWeek
      if(telephoneWeek.length === 7 || messageWeek.length === 7) {
        isCheckAll = true
      }
    }else{
      isCheckAll = true //默认初始化的
    }
    this.setState({
      visible: true,
      title: data.title,
      checkAll: isCheckAll,
      indeterminate: !isCheckAll

    }, () => {
    
      if (data.type === 1) {
        //电话信息回显
        localStorage.setItem('submitType', '1')
        //valueRuleList有值
        if (valueRuleList && valueRuleList.telephone) {
          let dayofWeek = valueRuleList.telephone.dayOfWeek 
          setFieldsValue({
            times: toWeekendsArr(dayofWeek) || [],
            beginTime: moment(valueRuleList.telephone.beginTime, format),
            endTime: moment(valueRuleList.telephone.endTime, format),
            gapMins: valueRuleList.telephone.mins,
            gapTimes: valueRuleList.telephone.times,
            isOpen: valueRuleList.isTelephone === 1 ? true : false,
          })
        } else {
          //电话
          //valueRuleList没值
          setFieldsValue({
            times:plainOptions, //默認全選
            beginTime: moment('00:00', format),
            endTime: moment('00:00', format),
            gapMins: 1,
            gapTimes: 1,
            isOpen: false,
          })
        }

      } else {
        //电话信息回显
        if (valueRuleList && valueRuleList.message) {
          let dayofWeek = valueRuleList.message.dayOfWeek 
          setFieldsValue({
            times: toWeekendsArr(dayofWeek) || [],
            beginTime: moment(valueRuleList.message.beginTime, format),
            endTime: moment(valueRuleList.message.endTime, format),
            gapMins: valueRuleList.message.mins,
            gapTimes: valueRuleList.message.times,
            isOpen: valueRuleList.isMessage === 1 ? true : false,
          })
        } else {
          //电话
          //valueRuleList没值
          setFieldsValue({
            times:plainOptions, //默認全選
            beginTime: moment('00:00', format),
            endTime: moment('00:00', format),
            gapMins: 1,
            gapTimes: 1,
            isOpen: false,
          })
        }
      }
    }

    );
  };
  handleCancel = e => {
    this.setState({
      visible: false,
    });
  };
  queryData = (offset = 1, size = ONE_PAGE_SIZE) => {
    const { dispatch } = this.props;

    dispatch({
      type: 'message/queryPage',
      payload: {
        pageNum: offset,
        pageSize: size,
      },
    });
  }
  initCurrent = () => {
    this.setState({
      current: 1
    })
  }
  onShowSizeChange = (current, pageSize) => {
    const { dispatch, cond } = this.props;
    // cond.pageSize = pageSize;
    dispatch({ type: `message/queryPage`, payload: {pageNum:1, pageSize} }).then(() => {
      this.initCurrent()
    })
  }

  render() {
    const { form, listSetting } = this.props;
    const { list = [], total = 0 } = listSetting
    const ans = Array.isArray(list) && list.map((item, ind) => ({
      id: item.id,
      idNum: ind + 1 < 10 ? `0${ind + 1}` : ind + 1,
      name: item.name,
      type: item.type,
      phone: item.telephone,
      valueRuleList: item.valueRuleList || {}
    })

    )
    const { getFieldDecorator } = form;
    const formItemLayout = {
      labelCol: {
        xs: { span: 12 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 12 },
        sm: { span: 16 },
      },
    };

    const pagination = {
      total,
      showTotal: total => `共 ${total} 条`,
      current: this.state.current,
      showSizeChanger: true,
      pageSizeOptions: ['10', '20', '50', '100'],
      onShowSizeChange: this.onShowSizeChange,
      onChange: (current) => {
        this.setState({ current })
        this.queryData(current)
      },
    };
    const columns = [
      {
        title: '序号',
        dataIndex: 'idNum',
        key: 'idNum'
      },
      {
        title: '通知对象',
        dataIndex: 'name',
        key: 'name'
      },
      {
        title: '电话',
        dataIndex: 'phone',
        key: 'phone'
      },

      {
        title: '通知', key: 'x', render: (record, text, index) => {
          const isTelephone = record.valueRuleList.isTelephone
          const isMessage = record.valueRuleList.isMessage
          let colorPhone = ''
          let colorMessage = ''
          //判断短信
          if (isMessage === 1) {
            colorMessage = '#0880DF'
          } else {
            colorMessage = '#E61219'
          }
          //判断电话
          if (isTelephone === 1) {
            colorPhone = '#0880DF'
          } else {
            colorPhone = '#E61219'
          }

          return (
            <div>
              <>
                <a onClick={() => { this.showModal(
                  { title: '电话通知', type: 1, targetObj: { ...record } }
                  ) }} 
                  style={{ marginRight: 20, color: `${colorPhone}` }}>电话通知</a>
              </>
              <>
              { record.phone.length === 11 &&
                <a onClick={() => { this.showModal(
                  { title: '短信通知', type: 2, targetObj: { ...record } }
                  ) }} 
                  style={{ color: `${colorMessage}` }}>短信通知</a>
              }
              </>
            </div>
          )
        }
      }];

    return (
      <>
        <Table
          columns={columns}
          pagination={pagination}
          dataSource={ans}
          bordered
          rowKey="id"
          loading={this.props.loading}
        />
        <Modal
          className={styles.myModal}
          width="50%"
          title={this.state.title}
          visible={this.state.visible}
          onOk={this.handleOk}
          onCancel={this.handleCancel}
        >
          <Form>
            <SearchRow>
              <SearchCol span={24} key={1}>
                <Form.Item
                  {...formItemLayout}
                  label='通知时间'
                >
                  <div>
                    <Checkbox
                      indeterminate={this.state.indeterminate}
                      onChange={this.onCheckAllChange}
                      checked={this.state.checkAll}
                    >
                      全选
                        </Checkbox>
                  </div>
                  <br />
                  {getFieldDecorator('times', {
                    rules: [{ required: true, message: '请选择星期' }],
                  })(

                    <CheckboxGroup
                      options={plainOptions}
                      // value={this.state.checkedList}
                      onChange={this.onChange}
                    />

                  )}
                </Form.Item>
              </SearchCol>


              <SearchCol key={4} span={24}>
                <Form.Item required={false} label='    ' {...formItemLayout}>
                  <div>
                    {
                      getFieldDecorator('beginTime', {
                        rules: [{ required: true, message: '请选择' }],
                      })(
                        <TimePicker format={format} style={{ marginRight: 20 }} />
                      )
                    }
                    ~ &nbsp;&nbsp;&nbsp;
                     {
                      getFieldDecorator('endTime', {
                        rules: [{ required: true, message: '请选择' }],
                      })(
                        <TimePicker format={format} />
                      )
                    }
                  </div>
                </Form.Item>
              </SearchCol>


              <SearchCol key={3} span={24}>
                <Form.Item required={false} label='    ' {...formItemLayout}>
                  <div>
                    <span>若不及时处理火警，则间隔</span>
                    {
                      getFieldDecorator('gapMins', {
                        rules: [{
                          message: '必填字段!',
                          required: true
                        }],
                      })(
                        <InputNumber min={1} max={10} style={{ margin: '0px 10px' }} />
                      )
                    }
                    <span>分钟再次推送，共推送</span>
                    {
                      getFieldDecorator('gapTimes', {
                        rules: [{
                          message: '必填字段!',
                          required: true
                        }],
                      })(
                        <InputNumber min={1} max={5} style={{ margin: '0px 10px' }} />
                      )
                    }
                    <span>次</span>
                  </div>
                </Form.Item>
              </SearchCol>



              <SearchCol key={2} span={24}>
                <Form.Item
                  label="是否开启"
                  {...formItemLayout}
                >
                  {getFieldDecorator('isOpen', {
                    rules: [{ required: true, message: '' }],
                    valuePropName: 'checked' //默认是value改成自定义checked
                  })(
                    <Switch style={{ marginTop: -5 }} />
                  )}
                </Form.Item>
              </SearchCol>

            </SearchRow>
          </Form>
        </Modal>
      </>
    )
  }
}
const FormList = Form.create<any>({ name: 'form_in_modal' })(MessageTable);
export default FormList;
